<template>
  <div class="app-container">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                   label-width="68px">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable
                        @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="签订时间">
              <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd"
                              type="daterange" range-separator="-" start-placeholder="开始日期"
                              end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini"
                         @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table v-loading="loading" height="400" :data="infoList"
                    @selection-change="handleSelectionChange" :row-style="{ height: '30px' }" border
                    :cell-style="{ padding: '0px' }" highlight-current-row>
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" type="index" align="center" prop="index"
                             :index="indexMethod"></el-table-column>
            <el-table-column label="合同名称" align="center" prop="contractName" width="180"
                             :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <!-- 使用按钮作为可点击元素，并绑定点击事件 -->
                  {{ scope.row.contractName }}
              </template>
            </el-table-column>
            <el-table-column label="合同金额" align="center" prop="contractAmount" :show-overflow-tooltip="true"
                             />
            <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true"
                              />
            <el-table-column label="签订时间" align="center" prop="signingTime" :show-overflow-tooltip="true"
                            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.signingTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>

            <el-table-column label="销售人员" align="center" prop="salespersonName"
                             :show-overflow-tooltip="true" />
            <el-table-column label="客户名称" align="center" prop="enterpriseName" width="180"
                             :show-overflow-tooltip="true" />
            <el-table-column label="状态" align="center" prop="state" >
              <template slot-scope="scope">
                <dict-tag :options="dict.type.contract_state" :value="scope.row.state"
                          :class="{ 'add-class': scope.row.state === '0', 'review-class': scope.row.state === '1', 'agree-class': scope.row.state === '2', 'cancel-class': scope.row.state === '3', }" />
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList" />
  </div>
   </template>

<script>
import { listContractInfo, delContractInfo, editMainClass, updateContractState } from "@/api/contract/info";
import MainType from "@/components/MainType/index"
import { listType } from "@/api/maintype/type";
import pdf from 'vue-pdf'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { download } from "@/utils/request";
import { queryFile, fileRemove } from "@/api/system/file";
export default {
  name: "contract",
  props: {
    enterpriseId: {
      type: String,
      default: null
    },
    enterpriseName: {
      type: String,
      default: null
    },
    telephone:{
      type:String,
      default:null
    },
  },
  dicts: ['contract_state'],
  components: { MainType,  pdf, Treeselect },
  data() {
    return {
      fileList: [],
      openFileList: false,
      optionData: null,
      titleClass: "修改主分类",
      openMainClass: false,
      dateRange: [],
      type: 0,
      classId: "",
      userType: "1",
      sign: '1',
      opt: 'add',
      refreshKey: 0,
      id: '',
      obj: null,
      index: null,
      dialogVisible: false,
      dialogVisiblePdf: false,
      dialogImageUrl: '',
      dialogImageUrlPdf: '',
      pageTotal: null,
      newIndex: '',
      edit: 'edit',
      uuid: "",
      typeCode: 'contractInfo',
      // 遮罩层
      loading: true,
      isClick: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        contractId: null,
        classificationId: null,
        contractName: null,
        relatedContractId: null,
        relatedContractName: null,
        contractAmount: null,
        signingTime: null,
        endTime: null,
        enterpriseId: null,
        enterpriseName: null,
        customerAddress: null,
        customerContact: null,
        telephone: null,
        salespersonId: null,
        salespersonName: null,
        additionalTerms: null,
        belongTo: null,
        creationId: null,
        creationName: null,
        creationTime: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        state: null
      },
      // 表单参数
      form: {},
      formClass: {},
      // 表单校验
      rules: {},
      cId: "",
      reContractId: "",
      reContractName: "",
    };
  },
  created() {
    this.listType();
    this.getList();
  },
  methods: {
    queryUploadFile(id) {
      queryFile(id, this.typeCode).then(response => {
        this.fileList = response.data;
        console.log(this.fileList)
      });
      this.openFileList = true;
    },
    handleDownload(fileUrl, fileName) {
      let params = {
        resource: fileUrl
      }
      download("/common/download/resource", params, fileName);
    },
    handleView(row) {
      if (row.url != null && row.url != '' && (row.url).indexOf('.pdf') !== -1) {
        this.handlePictureCardPreviewPdf(row.url);
      } else {
        this.handlePictureCardPreview(row.url);
      }
    },
    handleSubmit(row) {
      const contractInfo = {
        contractId: row.contractId
      }
      this.$modal.confirm('是否确认提交合同名称为"' + row.contractName + '"的数据项？').then(function () {
        updateContractState(contractInfo);
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
      }).catch(() => { });
    },
    listType() {
      listType({ typeCode: 'contractInfo' }).then(res => {
        this.optionData = res.data;
      })
    },
    cancelClass() {
      this.openMainClass = false;
      this.resetClass();
    },
    // 表单重置
    resetClass() {
      this.formClass = {
        classificationId: null,
      }
    },
    editMainClass() {
      this.listType();
      if (this.ids.length == 0) {
        this.$message.error("请选择要修改的合同信息！");
      } else {
        this.openMainClass = true;
      }
    },
    getNode(data, node, obj) {
      this.queryParams.classificationId = data.id;
      this.classId = data.id;
      this.getList()
    },
    close() {
      this.type = 2;
      this.getList();
    },
    guid() {
      function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
      }
      return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    },
    indexMethod(index) {
      return (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      if (this.enterpriseId != null) {
        this.queryParams.enterpriseId = this.enterpriseId;
      }
      if (this.enterpriseName !=null){
        this.queryParams.enterpriseName = this.enterpriseName;
      }
      if (this.telephone !=null){
        this.queryParams.telephone = this.telephone;
      }
      listContractInfo(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        contractId: null,
        classificationId: null,
        contractName: null,
        relatedContractId: null,
        relatedContractName: null,
        contractAmount: null,
        signingTime: null,
        endTime: null,
        enterpriseId: null,
        enterpriseName: null,
        customerAddress: null,
        customerContact: null,
        telephone: null,
        salespersonId: null,
        salespersonName: null,
        additionalTerms: null,
        belongTo: null,
        creationId: null,
        creationName: null,
        creationTime: null,
        operateTime: null,
        operateId: null,
        departmentId: null,
        departmentName: null,
        organizationId: null,
        organizationName: null,
        delFlag: null,
        state: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handlePictureCardPreview(url) {
      this.dialogImageUrl = url;
      this.dialogVisible = true;
    },
    handlePictureCardPreviewPdf(url) {
      this.pdfUrl = pdf.createLoadingTask(url)
      // 获取页码
      this.pdfUrl.promise.then(pdf => this.pageTotal = pdf.numPages).catch(error => {
      })
      this.dialogImageUrlPdf = url;
      this.dialogVisiblePdf = true;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.contractId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.uuid = this.guid();
      this.edit = "add";
      this.cId = this.uuid;
      this.isClick = true;
      this.type = 1;
    },
    handleSubView(row, index) {
      this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index;
      this.edit = "view";
      this.id = row.contractId;
      this.cId = row.contractId;
      this.type = 1;
    },
    /** 修改按钮操作 */
    handleUpdate(row, index) {
      this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index;
      this.edit = "edit";
      this.isClick = false;
      this.id = row.contractId;
      this.cId = row.contractId;
      this.type = 1
    },
    handleChange(row, index) {
      this.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index;
      this.uuid = this.guid();
      this.edit = "change";
      this.cId = this.uuid;
      this.isClick = true;
      this.type = 1;
      this.reContractId = row.contractId;
      this.reContractName = row.contractName;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const contractIds = row.contractId || this.ids;
      this.$modal.confirm('是否确认删除合同名称为"' + row.contractName + '"的数据项？').then(function () {
        return delContractInfo(contractIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
  }
};
</script>
<style>
.add-class {
  color: orange;
}

.review-class {
  color: #409EFF;
}

.agree-class {
  color: #4CE778;
}

.cancel-class {
  color: red;
}
</style>
